package cn.edu.baiyunu.myapplication.ui.upload

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import cn.edu.baiyunu.myapplication.data.model.PhotoSpec
import cn.edu.baiyunu.myapplication.data.repository.PhotoRepository
import cn.edu.baiyunu.myapplication.data.repository.PreferenceRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 上传页面ViewModel，负责管理照片上传状态和操作
 */
class UploadViewModel(
    private val photoRepository: PhotoRepository,
    private val preferenceRepository: PreferenceRepository
) : ViewModel() {

    // 上传页面状态
    enum class UploadScreenState {
        UPLOAD, // 上传选择界面
        CAMERA, // 相机拍摄界面
        PREVIEW, // 照片预览界面
    }

    // 上传页面当前状态
    private val _screenState = MutableStateFlow(UploadScreenState.UPLOAD)
    val screenState: StateFlow<UploadScreenState> = _screenState.asStateFlow()

    // 已选择的照片URI
    private val _selectedImageUri = MutableLiveData<Uri?>(null)
    val selectedImageUri: LiveData<Uri?> = _selectedImageUri

    // 已选择的照片位图
    private val _selectedImageBitmap = MutableLiveData<Bitmap?>(null)
    val selectedImageBitmap: LiveData<Bitmap?> = _selectedImageBitmap

    // 选择的规格类型(来自导航参数)
    private val _specType = MutableLiveData<String?>(null)
    val specType: LiveData<String?> = _specType

    // 上传状态消息
    private val _statusMessage = MutableLiveData<String?>(null)
    val statusMessage: LiveData<String?> = _statusMessage

    // 设置页面状态
    fun setScreenState(state: UploadScreenState) {
        _screenState.value = state
    }

    // 设置选择的照片URI
    fun setSelectedImageUri(uri: Uri?) {
        _selectedImageUri.value = uri
        if (uri != null) {
            _screenState.value = UploadScreenState.PREVIEW
        }
    }

    // 设置选择的照片位图
    fun setSelectedImageBitmap(bitmap: Bitmap?) {
        _selectedImageBitmap.value = bitmap
        if (bitmap != null) {
            _screenState.value = UploadScreenState.PREVIEW
        }
    }

    // 设置规格类型
    fun setSpecType(type: String?) {
        _specType.value = type
    }

    // 清除所选照片
    fun clearSelectedImage() {
        _selectedImageUri.value = null
        _selectedImageBitmap.value = null
        _screenState.value = UploadScreenState.UPLOAD
    }

    // 设置状态消息
    fun setStatusMessage(message: String?) {
        _statusMessage.value = message
        // 自动清除消息
        viewModelScope.launch {
            kotlinx.coroutines.delay(3000)
            _statusMessage.value = null
        }
    }

    // 保存位图到文件系统
    fun saveBitmapToFile(context: Context, bitmap: Bitmap): Uri? {
        return try {
            // 创建文件名
            val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
            val fileName = "PHOTO_$timeStamp.jpg"
            
            // 创建临时文件
            val storageDir = context.getExternalFilesDir("photos")
            val imageFile = File(storageDir, fileName)
            
            // 将位图保存到文件
            FileOutputStream(imageFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out)
            }
            
            // 返回文件URI
            Uri.fromFile(imageFile)
        } catch (e: Exception) {
            Log.e("UploadViewModel", "保存位图失败", e)
            null
        }
    }
}

/**
 * UploadViewModel工厂类
 */
class UploadViewModelFactory(
    private val photoRepository: PhotoRepository,
    private val preferenceRepository: PreferenceRepository
) : ViewModelProvider.Factory {
    
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(UploadViewModel::class.java)) {
            return UploadViewModel(photoRepository, preferenceRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
} 